//
//  MapViewController.m
//  FitTime
//
//  Created by 赵建平 on 16/3/31.
//  Copyright © 2016年 赵建平. All rights reserved.
//


#import <AMapNaviKit/AMapNaviKit.h>
#import <CoreMotion/CoreMotion.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import <AVKit/AVKit.h>
#import <AudioToolbox/AudioToolbox.h>
#import "MapViewController.h"
#import "SportView.h"
#import "MZTimerLabel.h"
#import "SportData.h"
#import "JPSearchBar.h"
#import "SearchView.h"

#define APIKEY @"612caf2047ce93b6a9b106c2cd1bed7a"

static SystemSoundID sound_queue = 1;

typedef enum : NSUInteger {
    TrailStart,//  轨迹开始绘制中
    TrailEnd, // 停止绘制
} Trail;

typedef NS_ENUM(NSUInteger, NavigationTypes) {
    NavigationTypeNone = 0,
    NavigationTypeSimulator, //  虚拟导航
    NavigationTypeGPS,  // 实时导航
};

@interface MapViewController ()<MAMapViewDelegate, AMapLocationManagerDelegate, AMapSearchDelegate ,UISearchBarDelegate, UIGestureRecognizerDelegate, cellDidSeletedDelegate, AMapNaviViewControllerDelegate, AMapNaviManagerDelegate>

@property (nonatomic, strong) SportView *popView;
@property (nonatomic, strong) SportView *downView;
@property (nonatomic, strong) MAMapView *mapView;
@property (nonatomic, strong) AMapLocationManager *locationManager;// 位置管理者
@property (nonatomic, assign) BOOL isFold; // 是否收起弹窗视图
@property (nonatomic, assign) BOOL isContinue; // 是否运动中
@property (nonatomic, assign) BOOL isFirst;
@property (nonatomic, strong) UIButton *pauseButton; //暂停
@property (nonatomic, strong) UIButton *finshedButton;//  结束
@property (nonatomic, strong) UIAlertController *alertController;
@property (nonatomic, strong) UILabel *velocityLabel; //  平均速度
@property (nonatomic, strong) MZTimerLabel*timeLabel; //  时间
@property (nonatomic, strong) UILabel *distanceLabel; //  距离
//  绘制轨迹属性
@property (nonatomic, strong) NSMutableArray *locationArray;//  位置数组
@property (nonatomic, strong) MAPolyline *polyline; //  轨迹线
@property (nonatomic, assign) Trail trail;  // 轨迹记录状态
@property (nonatomic, strong) MAPointAnnotation *startPoint; // 起点大头针
@property (nonatomic, strong) MAPointAnnotation *endPoint;// 终点大头针
@property (nonatomic, assign) NSTimeInterval sumTime; // 累计步行时间
@property (nonatomic, assign) CGFloat sumDistance; // 累计步行距离
@property (nonatomic, assign) NSInteger count; // 次数
@property (nonatomic, assign) CLLocationCoordinate2D preLocation;//记录上一次坐标
@property (nonatomic, strong) CLLocation *prevLocation; //记录上一次位置
/**
 *  走路
 */
@property (nonatomic, strong) CMPedometer *pedometer;

// CoreData
@property (nonatomic, strong) CoreDataManager *coreDataManager;
// 导航
@property (nonatomic, strong) JPSearchBar *searchBar;
@property (nonatomic, strong) AMapSearchAPI *search;
@property (nonatomic, strong) AMapGeoPoint *endLocation;

//  长按手势初始化
@property (nonatomic, strong) UILongPressGestureRecognizer *longPressGesture;
@property (nonatomic, strong) MAPointAnnotation *destinationPoint;
@property (nonatomic, strong) NSArray *pathPolylines;
@property (nonatomic, strong) SearchView *searchView;
@property (nonatomic, strong) NSMutableArray *datasource;
@property (nonatomic, strong) NSString *searchString; // 搜索名字
@property (nonatomic, assign) BOOL route;
@property (nonatomic, strong) UIButton *locationButton;

// 导航
@property (nonatomic, strong) AMapNaviManager *naviManager;
@property (nonatomic, strong) AMapNaviViewController *naviViewController;
@property (nonatomic, assign) NavigationTypes naviType;
@property (nonatomic) BOOL calRouteSuccess; // 指示是否算路成功


@end

@implementation MapViewController

#pragma mark - 懒加载
- (AMapLocationManager *)locationManager {
    if (!_locationManager) {
        _locationManager = [[AMapLocationManager alloc] init];
    }
    return _locationManager;
}

- (MAMapView *)mapView {
    if (!_mapView) {
        _mapView = [[MAMapView alloc] init];
        
    }
    return _mapView;
}

- (CMPedometer *)pedometer {
    if (!_pedometer) {
        self.pedometer = [[CMPedometer alloc] init];
    }
    return _pedometer;
}

- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBarHidden = NO;
    
    // 设置定位精度：最佳精度
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    // 设置距离过滤器为5米，表示每移动5米更新一次位置
    self.locationManager.distanceFilter = 5;
    // 将视图控制器自身设置为CLLocationManager的delegate
    // 因此该视图控制器需要实现CLLocationManagerDelegate协议
    self.locationManager.delegate = self;
    // 开始监听定位信息
    [self.locationManager startUpdatingLocation];
    
    //  划线状态 --- 开
    self.trail = TrailStart;
    [self.locationArray removeAllObjects];
    
}

// 定位失败时激发的方法
- (void)amapLocationManager:(AMapLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"定位失败: %@",error);
}
// 成功获取定位数据后将会激发该方法
- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location {
}


- (void)viewWillDisappear:(BOOL)animated {
    self.navigationController.navigationBarHidden = YES;
    _mapView.showsUserLocation = NO;
    self.mapView.delegate = nil;
    self.locationManager.delegate = nil;
    self.naviManager.delegate = nil;
    self.naviViewController.delegate = nil;
    [self.naviManager stopNavi];
    self.naviManager = nil;
    self.sumTime = 0;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.coreDataManager = [CoreDataManager shareCoreDataManager];
    
    self.locationArray = [NSMutableArray arrayWithCapacity:0];
    [MAMapServices sharedServices].apiKey = APIKEY;
    [AMapLocationServices sharedServices].apiKey =APIKEY;
    [AMapSearchServices sharedServices].apiKey = APIKEY;
    [AMapNaviServices sharedServices].apiKey =APIKEY;
    self.sumTime = 0;
    
    self.isFirst = YES;
    self.route = NO;
    
    [self createMapView];
    [self createDownView];
    [self createSearchBar];
    [self createSearchView];
    [self initSearchDelegate];
    [self initNaviManager];
    [self initNaviViewController];
    [self initFlySpeech];
    // 自定义返回按键
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"iconfont-fanhui-3"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(leftAction:)];
}

- (void)leftAction:(id)sender {
    
    self.navigationController.tabBarController.tabBar.hidden = NO;
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)initNaviManager
{
    if (_naviManager == nil)
    {
        _naviManager = [[AMapNaviManager alloc] init];
        [_naviManager setDelegate:self];
    }
}

- (void)initNaviViewController
{
    if (_naviViewController == nil)
    {
        _naviViewController = [[AMapNaviViewController alloc] initWithDelegate:self];
    }
}

#pragma mark - 创建视图
- (void)createMapView {
    self.mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, StatusBarHeight + 44, SCREENWIDTH, SCREENHEIGHT / 2 - StatusBarHeight - 44)];
    [self.view addSubview:self.mapView];
    self.mapView.delegate = self;
    self.mapView.mapType = MAMapTypeStandard;
    self.mapView.showsUserLocation = YES;
    [self.mapView setUserTrackingMode:MAUserTrackingModeFollow animated:YES];
    [self.mapView setZoomLevel:16.1 animated:YES];
    // 后台定位
    self.mapView.pausesLocationUpdatesAutomatically = NO;
    self.mapView.allowsBackgroundLocationUpdates = YES;
    
    _mapView.userInteractionEnabled = YES;
    //     长按手势
    self.longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
    self.longPressGesture.delegate = self;
    [self.mapView addGestureRecognizer:self.longPressGesture];
    
    //  定位按钮
    _locationButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _locationButton.frame = CGRectMake(40 * SCALEWIDTH, CGRectGetHeight(_mapView.bounds) - 60 * SCALEHEIGHT, 40 * SCALEWIDTH, 40 * SCALEWIDTH);
    _locationButton.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin;
    _locationButton.backgroundColor = [UIColor whiteColor];
    [_locationButton addTarget:self action:@selector(locateAction) forControlEvents:UIControlEventTouchUpInside];
    [_locationButton setImage:[UIImage imageNamed:@"location_yes"] forState:UIControlStateNormal];
    [_mapView addSubview:_locationButton];
    //  路径规划按钮
    UIButton *routeButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    routeButton.frame = CGRectMake(100 * SCALEWIDTH, CGRectGetHeight(_mapView.bounds) - 60 * SCALEHEIGHT, 40 * SCALEWIDTH, 40 * SCALEWIDTH);
    routeButton.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin;
    routeButton.backgroundColor = [UIColor whiteColor];
    [routeButton setImage:[UIImage imageNamed:@"path@2x"] forState:UIControlStateNormal];
    [routeButton addTarget:self action:@selector(routeButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [_mapView addSubview:routeButton];
    //  实时导航按钮
    UIButton *pathBUtton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    pathBUtton.frame = CGRectMake(160 * SCALEWIDTH, CGRectGetHeight(_mapView.bounds) - 60 * SCALEHEIGHT, 40 * SCALEWIDTH, 40 * SCALEWIDTH);
    pathBUtton.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin;
    pathBUtton.backgroundColor = [UIColor whiteColor];
    [pathBUtton setImage:[UIImage imageNamed:@"shishi.png"] forState:UIControlStateNormal];
    [pathBUtton addTarget:self action:@selector(pathAction) forControlEvents:UIControlEventTouchUpInside];
    [_mapView addSubview:pathBUtton];
    //  虚拟导航按钮
    UIButton *simulatorButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    simulatorButton.frame = CGRectMake(220 * SCALEWIDTH, CGRectGetHeight(_mapView.bounds) - 60 * SCALEHEIGHT, 40 * SCALEWIDTH, 40 * SCALEWIDTH);
    simulatorButton.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin;
    simulatorButton.backgroundColor = [UIColor whiteColor];
    [simulatorButton setImage:[UIImage imageNamed:@"xuni.png"] forState:UIControlStateNormal];
    [simulatorButton addTarget:self action:@selector(simulatorButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [_mapView addSubview:simulatorButton];
    //  收合Button
    UIButton *foldButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    foldButton.frame = CGRectMake(CGRectGetMaxX(_mapView.bounds) - 45 * SCALEWIDTH, CGRectGetHeight(_mapView.bounds) - 45 * SCALEHEIGHT, 40 * SCALEWIDTH, 40 * SCALEWIDTH);
    foldButton.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin;
    foldButton.backgroundColor = [UIColor clearColor];
    [foldButton setBackgroundImage:[UIImage imageNamed:@"fold"] forState:UIControlStateNormal];
    [foldButton addTarget:self action:@selector(foldButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [_mapView addSubview:foldButton];
}

- (void)createDownView {
    
    self.isFold = NO;
    self.isContinue = YES;
    
    self.downView = [[SportView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height / 2, SCREENWIDTH, self.view.frame.size.height / 2)];
    self.downView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.downView];
    
    //      downView上布局
    self.distanceLabel = [UILabel labelWithFrame:CGRectZero color:[UIColor clearColor] alignment:NSTextAlignmentCenter];
    [self.downView addSubview:self.distanceLabel];
    [self.distanceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.downView.mas_top).offset(10 * SCALEHEIGHT);
        make.centerX.equalTo(self.downView.mas_centerX);
        make.height.equalTo(@(50 * SCALEHEIGHT));
    }];
    self.distanceLabel.text = @"0.0";
    self.distanceLabel.font = [UIFont systemFontOfSize:50 *SCALEWIDTH];
    
    // 距离文字label
    UILabel *disLabel = [UILabel labelWithFrame:CGRectZero color:[UIColor clearColor] alignment:NSTextAlignmentCenter];
    [self.downView addSubview:disLabel];
    [disLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.distanceLabel.mas_bottom);
        make.centerX.equalTo(self.downView.mas_centerX);
        make.height.equalTo(@(20 * SCALEHEIGHT));
    }];
    if ([_sportType isEqualToString:@"走路"]) {
        
        // 如果计步服务可用
        if([CMPedometer isStepCountingAvailable])
        {
            disLabel.text = @"累计步数";
            self.distanceLabel.text = @"0";
            
            NSDate *localDate = [NSDate date];
            [self.pedometer startPedometerUpdatesFromDate:localDate withHandler:^(CMPedometerData * _Nullable pedometerData, NSError * _Nullable error) {
                self.distanceLabel.text = [NSString stringWithFormat:@"%@" , pedometerData.numberOfSteps];
            }];
        }
        else
        {
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您的设备不支持记步" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self.navigationController popViewControllerAnimated:YES];
                self.navigationController.tabBarController.tabBar.hidden = NO;
            }];
            
            [alertController addAction:alertAction];
            [self presentViewController:alertController animated:YES completion:nil];
        }
        
        
    } else {
        disLabel.text = [NSString stringWithFormat:@"本次%@总里程（公里）", self.sportType];
    }
    //  时间Label
    self.timeLabel = [MZTimerLabel new];
    [self.downView addSubview:self.timeLabel];
    [self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.downView.mas_top).offset(130 * SCALEHEIGHT);
        make.centerX.equalTo(self.downView.mas_centerX).offset(-100 * SCALEWIDTH);
        make.height.equalTo(@(30 * SCALEHEIGHT));
    }];
    self.timeLabel.text = @"00:00:00";
    self.timeLabel.font = [UIFont systemFontOfSize:30 * SCALEWIDTH];
    
    //  开始计时
    [self.timeLabel start];
    
    
    // 时间文字label
    UILabel *timLabel = [UILabel labelWithFrame:CGRectZero color:[UIColor clearColor] alignment:NSTextAlignmentCenter];
    [self.downView addSubview:timLabel];
    [timLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.timeLabel.mas_bottom);
        make.centerX.equalTo(self.timeLabel.mas_centerX);
        make.height.equalTo(@(20 * SCALEHEIGHT));
    }];
    timLabel.text = @"时长";
    
    //  平均速度Label
    self.velocityLabel = [UILabel labelWithFrame:CGRectZero color:[UIColor clearColor] alignment:NSTextAlignmentCenter];
    [self.downView addSubview:self.velocityLabel];
    [self.velocityLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.downView.mas_top).offset(130 * SCALEHEIGHT);
        make.centerX.equalTo(self.downView.mas_centerX).offset(100 * SCALEWIDTH);
        make.height.equalTo(@(30 * SCALEHEIGHT));
    }];
    self.velocityLabel.text = @"00'00''";
    self.velocityLabel.font = [UIFont systemFontOfSize:30 * SCALEWIDTH];
    // 时间文字label
    UILabel *velLabel = [UILabel labelWithFrame:CGRectZero color:[UIColor clearColor] alignment:NSTextAlignmentCenter];
    [self.downView addSubview:velLabel];
    [velLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.velocityLabel.mas_bottom);
        make.centerX.equalTo(self.velocityLabel.mas_centerX);
        make.height.equalTo(@(20 * SCALEHEIGHT));
    }];
    velLabel.text = @"配速（米/秒）";
    
    //  结束按钮
    if(!self.finshedButton) {
        
        self.finshedButton = [UIButton buttonWithTitle:@"finshed.png" frame:CGRectZero target:self action:@selector(finshedButtonAction)];
        [self.downView addSubview:self.finshedButton];
        [self.finshedButton mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.centerX.equalTo(self.downView.mas_centerX).offset(100 * SCALEWIDTH);
            make.bottom.equalTo(self.downView.mas_bottom).offset(-50 * SCALEHEIGHT);
            make.size.mas_equalTo(CGSizeMake(80 * SCALEWIDTH, 80 * SCALEWIDTH));
        }];
        self.finshedButton.layer.masksToBounds = YES;
        self.finshedButton.layer.cornerRadius = 40 * SCALEWIDTH;
    }
    
    //  暂停按钮
    if (!self.pauseButton) {
        
        self.pauseButton = [UIButton buttonWithTitle:@"pause.png" frame:CGRectZero target:self action:@selector(pauseButtonAction)];
        [self.downView addSubview:self.pauseButton];
        [self.pauseButton mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.centerX.equalTo(self.downView.mas_centerX).offset(-100 * SCALEWIDTH);
            make.bottom.equalTo(self.downView.mas_bottom).offset(-50 * SCALEHEIGHT);
            make.size.mas_equalTo(CGSizeMake(80 * SCALEWIDTH, 80 * SCALEWIDTH));
        }];
        self.pauseButton.layer.masksToBounds = YES;
        self.pauseButton.layer.cornerRadius = 40 * SCALEWIDTH;
    }
    
}

- (void)createSearchBar
{
    self.searchBar = [[JPSearchBar alloc] initWithFrame:CGRectMake(50, 25, SCREENWIDTH - 100, 50)];
    self.searchBar.placeholder = @"请输入目的地";
    self.searchBar.delegate = self;
    self.navigationItem.titleView = self.searchBar;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(rightBarAction)];
}

- (void)createSearchView
{
    _searchView = [[SearchView alloc] initWithFrame:CGRectMake(0, -SCREENHEIGHT / 2 - 100 , SCREENWIDTH, SCREENHEIGHT / 2 + 100)];
    [self.view addSubview:_searchView];
    _searchView.delegate = self;
}

#pragma mark -  Target Action
- (void)locateAction
{
    if (_mapView.userTrackingMode != MAUserTrackingModeFollow)
    {
        _mapView.userTrackingMode = MAUserTrackingModeFollow;
        [_mapView setZoomLevel:16.1 animated:YES];
    }
}

- (void)pauseButtonAction {
    [UIView animateWithDuration:0.5f animations:^{
        
        [self.mapView setUserTrackingMode:MAUserTrackingModeNone animated:YES];
        if (self.isContinue) {
            
            NSString *path = [[NSBundle mainBundle] pathForResource:@"sport_pause" ofType:@"mp3"];
            NSURL *url = [NSURL fileURLWithPath:path];
            
            OSStatus error = AudioServicesCreateSystemSoundID((__bridge CFURLRef)url, &sound_queue);
            if (error != kAudioServicesNoError) {
                NSLog(@"%d  %@", error, url);
            }
            //  开始播放声音
            AudioServicesPlaySystemSound((SystemSoundID)sound_queue);
            
            //  结束定位
            [self.locationManager stopUpdatingLocation];
            // 暂停时间
            [self.timeLabel pause];
            //  暂停时改为第一次状态 重新添加大头针
            self.isFirst = YES;
            self.trail = TrailEnd;
            
            [self.pauseButton setBackgroundImage:[[UIImage imageNamed:@"continue.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        } else {
            NSString *path = [[NSBundle mainBundle] pathForResource:@"sport_continue" ofType:@"mp3"];
            NSURL *url = [NSURL fileURLWithPath:path];
            
            OSStatus error = AudioServicesCreateSystemSoundID((__bridge CFURLRef)url, &sound_queue);
            if (error != kAudioServicesNoError) {
                NSLog(@"%d  %@", error, url);
            }
            //  开始播放声音
            AudioServicesPlaySystemSound((SystemSoundID)sound_queue);
            //  开始定位
            [self.locationManager startUpdatingLocation];
            
            [self.timeLabel start];
            self.trail = TrailStart;
            
            [self.pauseButton setBackgroundImage:[[UIImage imageNamed:@"pause.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        }
        self.isContinue = !self.isContinue;
    }];
}

- (void)finshedButtonAction {
    
    //  结束定位
    [self.locationManager stopUpdatingLocation];
    // 暂停时间
    [self.timeLabel pause];
    //  暂停时改为第一次状态 重新添加大头针
    self.isFirst = YES;
    self.trail = TrailEnd;
    CGFloat sumDistance = self.distanceLabel.text.floatValue;
    
    if (sumDistance > 0.10) {
        
        UIAlertAction *sure = [UIAlertAction actionWithTitle:@"结束并保存" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //  结束定位
            [self.locationManager stopUpdatingLocation];
            
            self.count = 1;
            
            if ([_sportType isEqualToString:@"走路"]) {
            CGFloat dis =  (self.distanceLabel.text.floatValue * 0.7);
             self.distanceBlock([NSString stringWithFormat:@"%f", dis], self.sumTime, self.count);
            } else {
             self.distanceBlock(self.distanceLabel.text, self.sumTime, self.count);
            }
            // CoreData 插入数据
            SportData *sportData = [NSEntityDescription insertNewObjectForEntityForName:@"SportData" inManagedObjectContext:self.coreDataManager.managedObjectContext];
            sportData.sumMileage = @(self.sumDistance);
            sportData.sumTime = @(self.sumTime / 3600);
            sportData.sumCount = @(1);
            
            [self.coreDataManager saveContext];
            
            self.navigationController.tabBarController.tabBar.hidden = NO;
            [self.navigationController popViewControllerAnimated:YES];
        }];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            //  开始定位
            [self.locationManager startUpdatingLocation];
            
            [self.timeLabel start];
            self.trail = TrailStart;
            
        }];
        self.alertController = [UIAlertController alertControllerWithTitle:nil message:@"是否结束本次运动" preferredStyle:UIAlertControllerStyleAlert];
        [_alertController addAction:sure];
        [_alertController addAction:cancel];
        
        [self presentViewController:_alertController animated:YES completion:^{
        }];
        
    } else {
        
        UIAlertAction *sure = [UIAlertAction actionWithTitle:@"结束运动" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [self.navigationController popViewControllerAnimated:YES];
            self.navigationController.tabBarController.tabBar.hidden = NO;
        }];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"继续运动" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
            //  开始定位
            [self.locationManager startUpdatingLocation];
            [self.timeLabel start];
            self.trail = TrailStart;
            
        }];
        self.alertController = [UIAlertController alertControllerWithTitle:nil message:@"此次运动距离太短，无法保存， 是否结束本次运动？" preferredStyle:UIAlertControllerStyleAlert];
        [_alertController addAction:sure];
        [_alertController addAction:cancel];
        
        [self presentViewController:_alertController animated:YES completion:^{
        }];
    }
}

- (void)rightBarAction {
    [self.searchBar resignFirstResponder];
    [self searchViewAnimation];
}

- (void)routeButtonAction {
    [self initRoute];
}

- (void)pathAction {
    _naviType = NavigationTypeGPS;
    [self routeCal];
}

- (void)simulatorButtonAction {
    _naviType = NavigationTypeSimulator;
    [self routeCal];
}

#pragma mark - GestureRecognizer Action
- (void)foldButtonAction
{
    if (!self.isFold) {
        [UIView animateWithDuration:0.5f animations:^{
            self.downView.frame = CGRectMake(0, SCREENHEIGHT - 100 * SCALEHEIGHT, SCREENWIDTH,SCREENHEIGHT / 2);
            //  展开时地图大小
            self.mapView.frame = CGRectMake(0, 64 , SCREENWIDTH, SCREENHEIGHT - 64 - 100 * SCALEHEIGHT);
        }];
        
    } else {
        [UIView animateWithDuration:0.5f animations:^{
            self.downView.frame = CGRectMake(0,SCREENHEIGHT / 2, SCREENWIDTH, SCREENHEIGHT / 2);
            //  收起时地图大小
            self.mapView.frame = CGRectMake(0, 64, SCREENWIDTH, SCREENHEIGHT / 2 - 64);
        }];
    }
    self.isFold = !self.isFold;
}

- (void)handleLongPress:(UILongPressGestureRecognizer *)gesture
{
    self.route = YES;
    if (gesture.state == UIGestureRecognizerStateBegan)
    {
        CLLocationCoordinate2D coordinate = [_mapView convertPoint:[gesture locationInView:_mapView] toCoordinateFromView:_mapView];
        
        // 添加标注
        if (_destinationPoint != nil)
        {
            // 清理
            [_mapView removeAnnotation:_destinationPoint];
            _destinationPoint = nil;
            
            [_mapView removeOverlays:_pathPolylines];
            _pathPolylines = nil;
        }
        
        _destinationPoint = [[MAPointAnnotation alloc] init];
        _destinationPoint.coordinate = coordinate;
        [_mapView addAnnotation:_destinationPoint];
    }
    
}

#pragma mark  -  UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    self.route = YES;
    [self.searchBar resignFirstResponder];
    [self searchViewAnimation];
    
    [self initSearch];
   
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    [UIView animateWithDuration:0.5f animations:^{
        _searchView.frame = CGRectMake(0, 64, SCREENWIDTH, SCREENHEIGHT / 2);
    }];
    return YES;
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    //构造AMapInputTipsSearchRequest对象，设置请求参数
    AMapInputTipsSearchRequest *tipsRequest = [[AMapInputTipsSearchRequest alloc] init];
    tipsRequest.keywords = searchText;
    //发起输入提示搜索
    [_search AMapInputTipsSearch: tipsRequest];
    
}

#pragma mark -  cellDidSeletedDelegate
- (void)cellDidSeletedWithLocation:(AMapGeoPoint *)location WithName:(NSString *)name
{
    [self.searchBar resignFirstResponder];
    self.route = YES;
    
    CLLocationCoordinate2D Loca;
    Loca.latitude = location.latitude;
    Loca.longitude = location.longitude;
    
    // 添加标注
    if (_destinationPoint != nil)
    {
        // 清理
        [_mapView removeAnnotation:_destinationPoint];
        _destinationPoint = nil;
        
        [_mapView removeOverlays:_pathPolylines];
        _pathPolylines = nil;
    }
    
    _destinationPoint = [[MAPointAnnotation alloc] init];
    _destinationPoint.coordinate = Loca;
    [_mapView addAnnotation:_destinationPoint];

    self.searchBar.text = name;
    [self searchViewAnimation];
    [self initSearch];
}

#pragma mark - 提示框动画
- (void)searchViewAnimation
{
    [UIView animateWithDuration:0.5f animations:^{
        _searchView.frame = CGRectMake(0, -SCREENHEIGHT / 2 - 100 , SCREENWIDTH, SCREENHEIGHT / 2 + 100);
    }];
}

- (void)initSearchDelegate {
    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;
}

#pragma mark - init        地图搜索  +++  地理编码
- (void)initSearch
{
    AMapGeocodeSearchRequest *geo = [[AMapGeocodeSearchRequest alloc] init];
    geo.address = self.searchBar.text;
    [self.search AMapGeocodeSearch:geo];
}



#pragma mark - init         路径规划
- (void)initRoute
{
    if (_destinationPoint == nil || _prevLocation == nil || _search == nil) {
        return;
    }
    // 设置为步行路径规划
    //    AMapWalkingRouteSearchRequest *walkingRequest = [[AMapWalkingRouteSearchRequest alloc] init];
    AMapDrivingRouteSearchRequest *walkingRequest = [[AMapDrivingRouteSearchRequest alloc] init];
    walkingRequest.origin = [AMapGeoPoint locationWithLatitude:self.prevLocation.coordinate.latitude longitude:self.prevLocation.coordinate.longitude];
    //    walkingRequest.destination = [AMapGeoPoint locationWithLatitude:self.destinationPoint.coordinate.latitude longitude:self.destinationPoint.coordinate.longitude];
    walkingRequest.destination = [AMapGeoPoint locationWithLatitude:self.destinationPoint.coordinate.latitude longitude:self.destinationPoint.coordinate.longitude];
    
    //    [self.search AMapWalkingRouteSearch:walkingRequest];
    //    walkingRequest.strategy = 2;//距离优先
    //    walkingRequest.requireExtension = YES;
    
    //发起路径搜索
    [_search AMapDrivingRouteSearch: walkingRequest];
}

- (void)initFlySpeech
{
    if (_iFlySpeechSynthesizer == nil) {
        _iFlySpeechSynthesizer = [IFlySpeechSynthesizer sharedInstance];
    }
    _iFlySpeechSynthesizer.delegate = self;
}

- (void)initAlert
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"没有搜索到结果哦😃" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alertController addAction:alertAction];
    [self presentViewController:alertController animated:YES completion:nil];
}


#pragma mark -   AMapSearchDelegate
//实现输入提示的回调函数
-(void)onInputTipsSearchDone:(AMapInputTipsSearchRequest*)request response:(AMapInputTipsSearchResponse *)response
{
    if(response.tips.count == 0)
    {
        return;
    }
    self.datasource = [NSMutableArray array];
    //通过AMapInputTipsSearchResponse对象处理搜索结果
    for (AMapTip *p in response.tips) {
        [self.datasource addObject:p];
    }
    if (self.datasource) {
         self.searchView.searchArr = self.datasource;
    }
}

#pragma mark - 地理编码
- (void)onGeocodeSearchDone:(AMapGeocodeSearchRequest *)request response:(AMapGeocodeSearchResponse *)response
{
    if (response.geocodes.count == 0) {
        [self initAlert];
        return;
    }
    //通过AMapGeocodeSearchResponse对象处理搜索结果
    for (AMapTip *p in response.geocodes) {
        
        CLLocationCoordinate2D loc;
        loc.latitude = p.location.latitude;
        loc.longitude = p.location.longitude;
        
        // 添加标注
        if (_destinationPoint != nil)
        {
            // 清理
            [_mapView removeAnnotation:_destinationPoint];
            _destinationPoint = nil;
            
            [_mapView removeOverlays:_pathPolylines];
            _pathPolylines = nil;
        }
        
        _destinationPoint = [[MAPointAnnotation alloc] init];
        [_mapView addAnnotation:_destinationPoint];
        
        _destinationPoint.coordinate = loc;
        
        [_mapView addAnnotation:_destinationPoint];
    }
    
}

- (void)onRouteSearchDone:(AMapRouteSearchBaseRequest *)request response:(AMapRouteSearchResponse *)response
{
    if (response.count > 0) {
        [_mapView removeOverlays:_pathPolylines];
        _pathPolylines = nil;
       
        //    只显示第一条
        _pathPolylines = [self polylinesForPath:response.route.paths[0]];
        [_mapView addOverlays:_pathPolylines];
        [_mapView showAnnotations:@[_destinationPoint, _mapView.userLocation] animated:YES];
        
    }
}

- (NSArray *)polylinesForPath:(AMapPath *)path
{
    if (path == nil || path.steps.count == 0)
    {
        return nil;
    }
    
    NSMutableArray *polylines = [NSMutableArray array];
    
    [path.steps enumerateObjectsUsingBlock:^(AMapStep *step, NSUInteger idx, BOOL *stop) {
        
        NSUInteger count = 0;
        CLLocationCoordinate2D *coordinates = [self coordinatesForString:step.polyline                                                    coordinateCount:&count
            parseToken:@";"];
        
        MAPolyline *polyline = [MAPolyline polylineWithCoordinates:coordinates count:count];
        [polylines addObject:polyline];
        
        free(coordinates), coordinates = NULL;
    }];
    
    return polylines;
}

//  字符串解析
- (CLLocationCoordinate2D *)coordinatesForString:(NSString *)string
                                 coordinateCount:(NSUInteger *)coordinateCount
                                      parseToken:(NSString *)token
{
    if (string == nil)
    {
        return NULL;
    }
    
    if (token == nil)
    {
        token = @",";
    }
    
    NSString *str = @"";
    if (![token isEqualToString:@","])
    {
        str = [string stringByReplacingOccurrencesOfString:token withString:@","];
    }
    else
    {
        str = [NSString stringWithString:string];
    }
    
    NSArray *components = [str componentsSeparatedByString:@","];
    NSUInteger count = [components count] / 2;
    if (coordinateCount != NULL)
    {
        *coordinateCount = count;
    }
    CLLocationCoordinate2D *coordinates = (CLLocationCoordinate2D*)malloc(count * sizeof(CLLocationCoordinate2D));
    
    for (int i = 0; i < count; i++)
    {
        coordinates[i].longitude = [[components objectAtIndex:2 * i]     doubleValue];
        coordinates[i].latitude  = [[components objectAtIndex:2 * i + 1] doubleValue];
    }
    
    return coordinates;
}

#pragma mark - MAMapViewDelegate

- (void)mapView:(MAMapView *)mapView didChangeUserTrackingMode:(MAUserTrackingMode)mode animated:(BOOL)animated
{
    if (mode == MAUserTrackingModeNone) {
        [_locationButton setImage:[UIImage imageNamed:@"location_no"] forState:UIControlStateNormal];
    } else {
        [_locationButton setImage:[UIImage imageNamed:@"location_yes"] forState:UIControlStateNormal];
    }
}

- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation
{
    //  开始状态 ——————————更新Label
    if (self.trail == TrailStart) {
       
     if (updatingLocation) {
    
        if (self.prevLocation) {
            
        // 计算本次定位数据与上次定位数据之间的时间差
        NSTimeInterval dtime = [userLocation.location.timestamp timeIntervalSinceDate:self.prevLocation.timestamp];
            
        // 计算本次定位数据与上次定位数据之间的距离
        CGFloat distance = [userLocation.location distanceFromLocation:self.prevLocation];
            
            if (distance > 5) {
                // 累计时间
                self.sumTime += dtime;
            }
        
        // (5米门限值，存储数组划线) 如果距离少于 5 米，则忽略本次数据直接返回该方法
        if (distance < 5) {
            NSLog(@"与前一更新点距离小于5m，直接返回该方法");
            return;
        }
            
        // 累加距离
        self.sumDistance += distance;
            if (![_sportType isEqualToString:@"走路"]) {
        self.distanceLabel.text = [NSString stringWithFormat:@"%.2f", self.sumDistance / 1000.0];
        }
        // 计算平均速度
        CGFloat avgSpeed  =self.sumDistance / self.sumTime;
        self.velocityLabel.text = [NSString stringWithFormat:@"%.2f", avgSpeed];
    
    }
    // 2. 将符合的位置点存储到数组中
    [self.locationArray addObject:userLocation.location];
    self.prevLocation = [self.locationArray lastObject];
         
        if (self.isFirst) {
            MAPointAnnotation *pointAnnotation = [[MAPointAnnotation alloc] init];
            pointAnnotation.coordinate = userLocation.coordinate;
            [self.mapView addAnnotation:pointAnnotation];
            
            self.preLocation = userLocation.coordinate;
            self.isFirst = NO;
            
        } else {
            
            if (self.preLocation.latitude != userLocation.coordinate.latitude || self.preLocation.longitude != userLocation.coordinate.longitude) {
                
                CLLocationCoordinate2D polyLineCoords[2];
                polyLineCoords[0] = self.preLocation;
                polyLineCoords[1] = userLocation.coordinate;
                
                MAPolyline *polyLine = [MAPolyline polylineWithCoordinates:polyLineCoords count:2];
                [self.mapView addOverlay:polyLine];
                self.preLocation = userLocation.coordinate;
                
          }
        }
      }
    }
    //  暂停状态更新上一个位置为当前用户位置
    if (self.trail == TrailEnd) {
        self.prevLocation = userLocation.location;
    }
}

- (MAOverlayView *)mapView:(MAMapView *)mapView viewForOverlay:(id<MAOverlay>)overlay
{
    if ([overlay isKindOfClass:[MAPolyline class]])
    {
        MAPolylineView *polylineView = [[MAPolylineView alloc] initWithPolyline:overlay];
        if (_route == YES) {
            polylineView.lineWidth   = 3;
            polylineView.strokeColor = [UIColor magentaColor];
        } else if (self.trail == TrailStart)
        {
            polylineView.lineWidth = 1.0f;
            if (self.velocityLabel.text.floatValue < 3) {
                polylineView.strokeColor = [UIColor greenColor];
            } else if (self.velocityLabel.text.floatValue < 5) {
                polylineView.strokeColor = [UIColor yellowColor];
            } else {
                polylineView.strokeColor = [UIColor redColor];
            }
        }
        
        return polylineView;
    }
    
    return nil;
}

//- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id <MAOverlay>)overlay {
//    
//    if (self.trail == TrailStart) {
//        if ([overlay isKindOfClass:[MAPolyline class]]) {
//            MAPolylineRenderer *render = [[MAPolylineRenderer alloc] initWithPolyline:overlay];
//            render.lineWidth = 1.0f;
//            render.lineCap = kCGLineCapRound;
//            render.lineJoin = kCGLineJoinRound;
//            
//            if (self.velocityLabel.text.floatValue < 3) {
//                render.strokeColor = [UIColor greenColor];
//            } else if (self.velocityLabel.text.floatValue < 5) {
//                render.strokeColor = [UIColor yellowColor];
//            } else {
//                render.strokeColor = [UIColor redColor];
//            }
//            
//            return render;
//        }
//    }
//    return nil;
//}
#pragma mark - 添加大头针
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation {
    
    if (annotation == _destinationPoint) {
        static NSString *reuseIndentifer = @"startReuseIndentifier";
        MAPinAnnotationView *annotationView = (MAPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndentifer];
        if (annotationView == nil) {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIndentifer];
        }
        annotationView.canShowCallout = YES;
        annotationView.animatesDrop = YES;
        annotationView.pinColor = MAPinAnnotationColorRed;
        return annotationView;
    }
    
    
    if ([annotation isKindOfClass:[MAPointAnnotation class]]) {
        static NSString *pointReuseIndentifer = @"pointReuseIndentifier";
        MAPinAnnotationView *annotationView = (MAPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifer];
        if (annotationView == nil)
        {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifer];
        }
        annotationView.canShowCallout= YES;       //设置气泡可以弹出，默认为NO
        annotationView.animatesDrop = YES;        //设置标注动画显示，默认为NO
        annotationView.draggable = NO;        //设置标注可以拖动，默认为NO
   
        annotationView.pinColor = MAPinAnnotationColorPurple;
       
        return annotationView;
    }
    return nil;
}


#pragma mark - 导航++++++++++++++++路径规划
- (void)routeCal
{
    AMapNaviPoint *startPoint = [AMapNaviPoint locationWithLatitude:self.prevLocation.coordinate.latitude longitude:self.prevLocation.coordinate.longitude];
    AMapNaviPoint *endPoint = [AMapNaviPoint locationWithLatitude:self.destinationPoint.coordinate.latitude longitude:self.destinationPoint.coordinate.longitude];
    
    NSArray *startPoints = @[startPoint];
    NSArray *endPoints   = @[endPoint];
    
    //驾车路径规划（未设置途经点、导航策略为速度优先）
    [_naviManager calculateDriveRouteWithStartPoints:startPoints endPoints:endPoints wayPoints:nil drivingStrategy:0];
    
    //步行路径规划
//    [self.naviManager calculateWalkRouteWithStartPoints:startPoints endPoints:endPoints];
}

- (void)naviViewControllerCloseButtonClicked:(AMapNaviViewController *)naviViewController
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
        [self.iFlySpeechSynthesizer stopSpeaking];
    });
   
    [self.naviManager stopNavi];
    
    [self.naviManager dismissNaviViewControllerAnimated:YES];
}

//路径规划成功的回调函数
- (void)naviManagerOnCalculateRouteSuccess:(AMapNaviManager *)naviManager
{
    //导航视图展示
    [_naviManager presentNaviViewController:_naviViewController animated:YES];
    
    _calRouteSuccess = YES;
}

//导航视图被展示出来的回调函数
- (void)naviManager:(AMapNaviManager *)naviManager didPresentNaviViewController:(UIViewController *)naviViewController
{
    //调用startGPSNavi方法进行实时导航，调用startEmulatorNavi方法进行模拟导航
    if (_naviType == NavigationTypeSimulator) {
        [_naviManager startEmulatorNavi];
    } else if (_naviType == NavigationTypeGPS) {
        [_naviManager startGPSNavi];
    }
    
}

- (void)naviManager:(AMapNaviManager *)naviManager playNaviSoundString:(NSString *)soundString soundStringType:(AMapNaviSoundType)soundStringType
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
        [_iFlySpeechSynthesizer startSpeaking:soundString];//soundString播报语
    });
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
